<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/2/17
 * Time: 16:00
 */

namespace app\astrologer\controller\v4;

use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\SystemConfig;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\exception\ApiException;
use app\common\model\AstrologerSettingUser;
use app\common\model\AstroSettingUser1751;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsRecode;
use think\Log;
use think\response\Json;

/**
 * 星盘
 * Class Astrolabe
 * @package app\api\controller\v8
 */
class AstrolabeController extends AstrAuth
{

    /**
     * 档案id1 和 档案id2 的盘 的参数
     */
    const PARAMS_DOUBLE = ['composite_thirdprogressed', 'synastry', 'composite_progressions', 'davison', 'marks', 'synastry_thirdprogressed', 'synastry_progressions', 'davison_thirdprogressed', 'davison_progressions', 'marks_thirdprogressed', 'marks_progressions',];

    /**
     * 带档案id的盘
     */
    const PARAMS_SINGLE = ['natal', 'transits', 'thirdprogressed', 'thirdprogressedvsnatal', 'progressions', 'progressionsvsnatal', 'solar', 'solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal', 'firdaria', 'profection', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa'];

    /**
     * 推运的盘，推运时间 datetime 和 时区timezone
     */
    const PARAMS_ADVANCE = ['now', 'transits', 'thirdprogressed', 'thirdprogressedvsnatal', 'progressions', 'progressionsvsnatal', 'solar', 'solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal', 'firdaria', 'profection', 'composite_thirdprogressed', 'composite_progressions', 'synastry_thirdprogressed', 'synastry_progressions', 'davison_thirdprogressed', 'davison_progressions', 'marks_thirdprogressed', 'marks_progressions',];


    /**
     * 合盘需要的所有参数，用于判断 两个档案是否反向
     */
    const PARAMS_SYNASTRY = ['synastry', 'synastry_thirdprogressed', 'synastry_progressions', 'composite', 'composite_thirdprogressed', 'composite_progressions', 'davison', 'davison_thirdprogressed', 'davison_progressions', 'marks', 'marks_thirdprogressed', 'marks_progressions', 'natal'];

    /**
     * 星盘设置需要使用
     */
    const DEFAULT_CONFIGURATION = [
        'planet' => [
            0 => [0, 0],
            1 => [0, 0],
            2 => [0, 0],
            3 => [0, 0],
            4 => [0, 0],
            5 => [0, 0],
            6 => [0, 0],
            7 => [0, 0],
            8 => [0, 0],
            9 => [0, 0],
            10 => [0, 0],
            11 => [0, 0],
            12 => [0, 0],
            13 => [0, 0],
            14 => [0, 0],
            15 => [0, 0],
            16 => [0, 0],
            17 => [0, 0],
            18 => [0, 0],
            19 => [0, 0],
            20 => [0, 0],
        ],
        'phase' => [
            0 => [0, 0],
            60 => [0, 0],
            90 => [0, 0],
            120 => [0, 0],
            180 => [0, 0],
            45 => [0, 0],
            135 => [0, 0],
            30 => [0, 0],
            150 => [0, 0],
            72 => [0, 0],
            144 => [0, 0],
            108 => [0, 0],
            36 => [0, 0],
        ],
        'arabic' => [
            0 => [0, 0],
            1 => [0, 0],
            2 => [0, 0],
            3 => [0, 0],
            4 => [0, 0],
            5 => [0, 0],
            6 => [0, 0],
            7 => [0, 0],
            8 => [0, 0],
            9 => [0, 0],
            10 => [0, 0],
            11 => [0, 0],
            12 => [0, 0],
            13 => [0, 0],
            14 => [0, 0],
            15 => [0, 0],
            16 => [0, 0],
            17 => [0, 0],
            18 => [0, 0],
            19 => [0, 0],
            20 => [0, 0],
            21 => [0, 0],
            22 => [0, 0],
            23 => [0, 0],
            24 => [0, 0],
            25 => [0, 0],
            26 => [0, 0],
        ],
        'h_sys' => 'p',
        'ecliptic' => 0,
        'zodrel' => 'p17',
        'firdaria' => 0,
        'profection_push_direction' => 0,
        'decanates' => 0,
        'bound_type' => 0,
        'ayanamsa' => 0,
        'location_use' => 0,
    ];

    /**
     * ---------- 仅【准有好事】端  连线咨询 使用
     * 查看星盘-占星师后台回答问题、占星师后台考试简单题查看星盘
     * @param string    chart   需要请求的星盘
     * @param int       tid     星盘类型 [1-3] 现代 古典 特殊
     * @param int       qid     占星师回答的问题id
     * @param string       access_token     占星师后台的access_token
     * @return Json
     * @throws ApiException
     * @throws \Exception
     */
    public function astrolabe_astrologer()
    {
        //检查参数
        $param = $this->request->param();
        $check = $this->checkParamAstro($param, true);
        if ($check !== true)
        {
            return show(config('code.error'), $check);
        }
        $astrInfo = $this->astrInfo;

        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, 1, $astrInfo['id']);   // 此处 app_type 参数 无效
        $rids = isset($astrNowConsultRtcInfo['recode_datas']) ? array_column($astrNowConsultRtcInfo['recode_datas'], 'rid') : [];
        if (isset($param['record1']) && $param['record1'] !== 'undefined' && !in_array($param['record1'], $rids))
        {
            return show(config('code.error'), '服务异常，档案不存在');
        }
        if (isset($param['record2']) && $param['record2'] !== 'undefined' && !in_array($param['record2'], $rids))
        {
            return show(config('code.error'), '服务异常，档案不存在');
        }
        //状态检查完成，开始实际业务
        $param['chart'] = (string)$param['chart'];
        $param['tid'] = (int)$param['tid'];
        $tid = 1;// 星盘配置方案使用默认值
        (isset($param['tid']) && in_array($param['tid'], [1, 2, 3], true)) && $tid = $param['tid'];
        //判断占星师是否绑定了app账户
        if ($astrInfo['uid'])
        {
            try
            {
                $settingData = (new AstroSettingUser1751())->getUserSettingByTid([
                    'uid' => $astrInfo['uid'],
                    'tid' => $tid,
                    'chart' => $param['chart'],
                ]);
            }
            catch (\Exception $e)
            {
                Log::write('获取token查看星盘，这里是：1.后台-》直播管理-》查看直播-》弹幕列表-》点击一个-》查看用户星盘；2.后台/主播管理员h5-》看盘详情；' . $param['access_token'] . ',error:' . $e->getMessage(), 'log', true);
                $settingData = (new AstroSettingUser1751())->getUserSettingByTid([
                    'uid' => 0,
                    'tid' => $tid,
                    'chart' => $param['chart'],
                ]);
            }
        } else
        {
            if (isset($astrInfo['id']))
            {
                try
                {
                    $settingData = (new AstrologerSettingUser())->getUserSettingByTid([
                        'uid' => $astrInfo['id'],
                        'tid' => $tid,
                        'chart' => $param['chart'],
                    ]);
                    if ($settingData['is_default'])
                    {
                        $settingData = (new AstroSettingUser1751())->getUserSettingByTid([
                            'uid' => 0,
                            'tid' => $tid,
                            'chart' => $param['chart'],
                        ]);
                    }
                }
                catch (\Exception $e)
                {
                    $settingData = (new AstroSettingUser1751())->getUserSettingByTid([
                        'uid' => 0,
                        'tid' => $tid,
                        'chart' => $param['chart'],
                    ]);
                }
            } else
            {
                Log::write('查看公共星盘错误，$astrInfo里的id为空！', 'error');
            }
        }

        $recodeModel = new ZyhsRecode();
        $Astrolog = Astrolog::getInstance();
        $record1 = '';
        $record2 = '';//用于合盘返回 ***$record2_name的UI
        if (isset($param['record1']))
        {
            $record1 = $recodeModel->getInfoById($param['record1']);
        }
        if (isset($param['record2']))
        {
            $record2 = $recodeModel->getInfoById($param['record2']);
        }
        //如果是合盘（星盘不会传is_recode_reverse参数），那么返回用户的昵称，用于显示 * in *
        if (isset($param['is_recode_reverse']) && (int)$param['is_recode_reverse'] === 1 && in_array($param['chart'], self::PARAMS_SYNASTRY))
        {
            if ($record2)
            {
                $Astrolog->setRecode1($record2);
            }
            if ($record1)
            {
                $Astrolog->setRecode2($record1);
            }
        } else
        {
            if ($record1)
            {
                $Astrolog->setRecode1($record1);
            }
            if ($record2)
            {
                $Astrolog->setRecode2($record2);
            }
        }

        if (isset($param['datetime']) && $param['datetime'] !== '')
        {
            $advanceTime = strtotime($param['datetime']);

            if ($advanceTime === false)
            {
                return show(config('code.error'), '时间格式异常');
            }

            [$year, $month, $day, $hour, $minute, $is_summer] = explode(',', date('Y,m,d,H,i,I', $advanceTime));

            $advanceInfo = [
                'year' => $year * 1,
                'month' => $month * 1,
                'day' => $day * 1,
                'hour' => $hour * 1,
                'minute' => $minute * 1,
                'timezone' => $param['timezone'] * 1,
                'is_summer' => $is_summer * 1,
            ];
            if (isset($param['longitude']))
            {
                $advanceInfo['longitude'] = $param['longitude'];
            }
            if (isset($param['latitude']))
            {
                $advanceInfo['latitude'] = $param['latitude'];
            }
            $Astrolog->setAdvance($advanceInfo);
        }
        $userSetting = [$param['chart'] => $settingData];
        // 法达参数数字转为字符串
        if (isset($userSetting[$param['chart']]['firdaria']))
        {
            if ($userSetting[$param['chart']]['firdaria'] === 0)
            {
                $userSetting[$param['chart']]['firdaria'] = 'default';
            } else
            {
                $userSetting[$param['chart']]['firdaria'] = 'another';
            }
        }
        // 界主星参数数字转为字符串
        if (isset($userSetting[$param['chart']]['bound_type']))
        {
            if ($userSetting[$param['chart']]['bound_type'] === 0)
            {
                $userSetting[$param['chart']]['bound_type'] = 'default';
            } else
            {
                $userSetting[$param['chart']]['bound_type'] = 'ptolemy_world';
            }
        }
        $data = $Astrolog->setExecPrefix(config('astrolog.prefix'))
            ->setIsAstrolabe(true)
            ->setUserSetting($userSetting)
            ->setVersion(2)
            ->setGetDatas([$param['chart']])
            ->getAstroDatas()
            ->getDatas($param['chart']);

        $error = $Astrolog->getError();
        if ($error)
        {
            Log::write('index:' . $error);

            return show(config('code.error'), $error);
        }

        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'dodekatemorion', 'trimsamsa', 'zodrel', 'fortune']))
        {
            $data['extent_type'] = $settingData['bound_type'] ?? 0;
        }
        //  获取系统配置
        $config = (new SystemConfig())->getSystemConfig(['title1', 'title_intro1', 'title2', 'title_intro2']);
        if ($param['chart'] === 'natal')
        {
            $astro_config = config('astro');
            $data['icon_info'] = [
                'horoscope_name' => $astro_config['horoscope_name'],
                'divination_name' => $astro_config['divination_name'],
                'status' => $astro_config['status'],
            ];
            $data['natal_report_name'] = (isset($config['title1']) && !empty($config['title1'])) ? $config['title1'] : '';
        }

        //如果是合盘（星盘不会传is_recode_reverse参数），那么返回用户的昵称，用于显示 * in *
        if (isset($param['is_recode_reverse']) && in_array($param['chart'], self::PARAMS_SYNASTRY))
        {
            if ($record1 && isset($record1['name']))
            {
                $data['record1_name'] = $record1['name'];
            }

            if ($record2 && isset($record2['name']))
            {
                $data['record2_name'] = $record2['name'];
            }

        }
        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 获取星盘配置
     * @method GET
     * @return \think\response\Json
     * @throws ApiException
     */
    public function astrologer_setting_index()
    {
        $param = request()->only(['tid', 'chart']);

        $validate = validate('Astroset');
        if (!$validate->scene('index')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }
        //校验access_token
        $astrInfo = $this->astrInfo;
        $param['chart'] = strtolower($param['chart']);
        //判断占星师是否绑定了app账户
        if (isset($astrInfo['uid']) && 0 !== (int)$astrInfo['uid'])
        {//绑定了app用户
            $map = ['uid' => (int)$astrInfo['uid'], 'chart' => $param['chart'], 'tid' => $param['tid']];
            $AstroSettingUserModel = new AstroSettingUser1751();
            $data = $AstroSettingUserModel->getUserSettingByTid($map);
        } else
        {//没有绑定app用户
            $map = ['uid' => (int)$astrInfo['id'], 'chart' => $param['chart'], 'tid' => $param['tid']];
            $AstroSettingUserModel = new AstrologerSettingUser();
            $data = $AstroSettingUserModel->getUserSettingByTid($map);
            if ($data['is_default'])
            {
                $data = (new AstroSettingUser1751())->getUserSettingByTid($map);
            }
        }

        $astroConfig = config('astroset1751');
        if (isset($data['asp_orb_all']) && $data['asp_orb_all'])
        {
            $arr = $this->OldAstroData($param, $data, $astroConfig);
        } else
        {
            if (count($data) === 1 && isset($data['is_default']))
            {
                return show(config('code.error'), '未设置默认值');
            }
            $arr = $this->NewAstroData1($param, $data, $astroConfig);
        }

        return show(config('code.success'), '加载成功', $arr);
    }

    /**
     * 更新星盘配置
     * @method POST
     * @return \think\response\Json
     * @throws ApiException
     */
    public function astrologer_setting_update()
    {
        // 新增盘只有整宫制
        $param = $this->request->only(['chart_value', 'tid', 'chart']);

        $requestData = json_decode($param['chart_value'], true);
        $requestData['chart'] = strtolower((string)$param['chart']);
        $requestData['tid'] = (int)$param['tid'];
        $checkData = $this->checkParamAstroSetting($requestData);
        if ($checkData !== true)
        {
            return show(config('code.error'), $checkData);
        }
        // 初始化更新后的配置，保证数据纯净
        $data = self::DEFAULT_CONFIGURATION;
        // 行星数据
        foreach ($data['planet'] as $pid => $planet)
        {
            if ($pid < 10)
            {
                $data['planet'][$pid][0] = (int)$requestData['planet']['list'][$pid]['status'];

                // 容许度
                if ($requestData['tid'] !== 1)
                {
                    $data['planet'][$pid][1] = (float)$requestData['planet']['list'][$pid]['allowedness'];
                }
            } // 虚点数据
            elseif ($pid >= 10 && $pid < 17)
            {
                $data['planet'][$pid][0] = (int)$requestData['little_planet']['list'][$pid - 10]['status'];
                // 虚点容许度
                if ($requestData['tid'] !== 1)
                {
                    $data['planet'][$pid][1] = (float)$requestData['little_planet']['list'][$pid - 10]['allowedness'];
                }
            }//
            else
            {
                $data['planet'][$pid][0] = (int)$requestData['four_axis']['list'][$pid - 17]['status'];
                // 四轴容许度
                if ($requestData['tid'] !== 1)
                {
                    $data['planet'][$pid][1] = (float)$requestData['four_axis']['list'][$pid - 17]['allowedness'];
                }
            }
        }
        // 希腊点数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'transits', 'synastry', 'divination']))
        {
            foreach ($data['arabic'] as $aid => $arabic)
            {
                if (isset($requestData['arabic']['list'][$aid]))
                {
                    $data['arabic'][$aid][0] = (int)$requestData['arabic']['list'][$aid]['status'];
                }
                // 希腊点容许度 希腊点容许度暂不支持20190801
            }
        }
        // 相位数据
        foreach ($requestData['phase']['list'] as $k => $datum)
        {
            foreach ($data['phase'] as $phid => $phase)
            {
                if ((int)$datum['name'] === $phid)
                {
                    $data['phase'][$phid][0] = (int)$datum['status'];
                    // 相位容许度
                    if ($requestData['tid'] !== 2)
                    {
                        $data['phase'][$phid][1] = (float)$datum['allowedness'];
                    }
                }
            }
        }
        // 分宮制数据
        foreach ($requestData['h_sys']['list'] as $k => $datum)
        {
            if ((int)$datum['status'] === 1)
            {
                $data['h_sys'] = (string)$datum['thumb'];
                break;
            }
        }
        // 法达数据
        if (strcasecmp($param['chart'], 'firdaria') === 0)
        {
            foreach ($requestData['firdaria']['list'] as $k => $datum)
            {
                if ((int)$datum['status'] === 1)
                {
                    $data['firdaria'] = (int)$datum['id'];
                }
            }
        }
        // 小限推运数据
        if (strcasecmp($param['chart'], 'profection') === 0)
        {
            foreach ($requestData['profection_push_direction']['list'] as $k => $datum)
            {
                if ((int)$datum['status'] === 1)
                {
                    $data['profection_push_direction'] = (int)$datum['id'];
                }
            }
        }
        // 十度主星数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination']))
        {
            foreach ($requestData['decanates']['list'] as $k => $datum)
            {
                if ((int)$datum['status'] === 1)
                {
                    $data['decanates'] = (int)$datum['id'];
                }
            }
        }
        // 界主星数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination']))
        {
            foreach ($requestData['bound_type']['list'] as $k => $datum)
            {
                if ((int)$datum['status'] === 1)
                {
                    $data['bound_type'] = (int)$datum['id'];
                }
            }
        }

        if (isset($requestData['location_use']['list']) && in_array($param['chart'], ['solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal'], true))
        {
            foreach ($requestData['location_use']['list'] as $k => $datum)
            {
                if ((int)$datum['status'] === 1)
                {
                    $data['location_use'] = (int)$datum['id'];
                }
            }
        }

        $param['chart_value'] = json_encode($data, true);
        $param['tid'] = $requestData['tid'];
        //校验access_token
        $astrInfo = $this->astrInfo;
        if (isset($astrInfo['uid']) && 0 !== (int)$astrInfo['uid'])
        {//绑定了app的uid
            $param['uid'] = (int)$astrInfo['uid'];
            if (!(new AstroSettingUser1751())->updateUserSetting($param))
            {
                return show(config('code.error'), '更新配置失败');
            }
        } else
        {//没有绑定app的uid
            $param['uid'] = (int)$astrInfo['id'];
            if (!(new AstrologerSettingUser())->updateUserSetting($param))
            {
                return show(config('code.error'), '更新配置失败');
            }
        }
        return show(config('code.success'), '更新配置成功');
    }

    /**
     * 还原星盘配置
     * @method DELETE
     * @return \think\response\Json
     * @throws ApiException
     */
    public function astrologer_setting_restore()
    {
        if (!$this->request->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = $this->request->only(['tid', 'chart']);

        $validate = validate('Astroset');

        if (!$validate->scene('delete')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        //校验access_token
        $astrInfo = $this->astrInfo;
        if (isset($astrInfo['uid']) && 0 !== (int)$astrInfo['uid'])
        {//绑定了app的uid
            $param['uid'] = $astrInfo['uid'];
            if (!(new AstroSettingUser1751())->restoreUserSetting($param))
            {
                return show(config('code.error'), '还原失败');
            }
        } else
        {//没有绑定app的uid
            $param['uid'] = $astrInfo['id'];
            if (!(new AstrologerSettingUser())->restoreUserSetting($param))
            {
                return show(config('code.error'), '还原失败');
            }
        }

        return show(config('code.success'), '还原成功');
    }

    /**
     * 新星盘数据格式重组
     * @param $param
     * @param $data
     * @param $astroConfig
     * @return array
     */
    public function NewAstroData1($param, $data, $astroConfig)
    {
        $arr = [];
        $isAncient = $param['tid'] == 2;
        //行星数据
        foreach ($data['planet'] as $k => $datum)
        {
            switch (true)
            {
                //行星
                case in_array($k, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
                    $tmp = [
                        'id' => $k,
                        'name' => $astroConfig['planet']['name'][$k],
                        'status' => $datum[0],
                        'allowedness' => $datum[1],
                    ];
                    $arr['planet']['list'][] = $tmp;
                    $arr['planet']['select_status'] = $astroConfig['planet']['select_status'];
                    $arr['planet']['title'] = $astroConfig['planet']['title'];
                    break;
                //虚点
                case in_array($k, [10, 11, 12, 13, 14, 15, 16]):
                    $tmp = [
                        'id' => $k,
                        'name' => $astroConfig['planet']['name'][$k],
                        'status' => $datum[0],
                        'allowedness' => $datum[1],
                    ];
                    $arr['little_planet']['list'][] = $tmp;
                    $arr['little_planet']['select_status'] = $astroConfig['planet']['select_status'];
                    $arr['little_planet']['title'] = '虚点';
                    break;
                //四轴
                case in_array($k, [17, 18, 19, 20]):
                    $tmp = [
                        'id' => $k,
                        'name' => $astroConfig['planet']['name'][$k],
                        'status' => $datum[0],
                        'allowedness' => $datum[1],
                    ];
                    $arr['four_axis']['list'][] = $tmp;
                    $arr['four_axis']['select_status'] = $astroConfig['planet']['select_status'];
                    $arr['four_axis']['title'] = '四轴';
                    break;
            }
        }
        // 相位数据
        $num = 0;
        // 新增相位108
        if (!isset($data['phase'][108]))
        {
            $data['phase'][108] = [0, 1];
        }
        if (!isset($data['phase'][36]))
        {
            $data['phase'][36] = [0, 1];
        }
        foreach ($data['phase'] as $k => $datum)
        {
            $tmp = [
                'id' => $num,
                'name' => $astroConfig['phase']['name'][$num] . '˚',
                'status' => $datum[0],
                'allowedness' => $datum[1],
            ];
            $arr['phase']['list'][] = $tmp;
            $arr['phase']['select_status'] = $astroConfig['phase']['select_status'];
            $num += 1;
        }
        $arr['planet']['allowedness_switch'] =
        $arr['little_planet']['allowedness_switch'] =
        $arr['four_axis']['allowedness_switch'] = $param['tid'] > 1 ? 1 : 0;
        $arr['phase']['allowedness_switch'] = $isAncient ? 0 : 1;
        $arr['phase']['title'] = '相位';
        // 希腊点数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'transits', 'synastry', 'divination']))
        {
            foreach ($data['arabic'] as $k => $datum)
            {
                // 过滤只显示到朔望点，后面的希腊点禁止开关
                if ($k > 8) break 1;

                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['arabic']['name'][$k],
                    'status' => $datum[0],
                ];
                $arr['arabic']['list'][] = $tmp;
            }
            $arr['arabic']['select_status'] = $astroConfig['arabic']['select_status'];
            $arr['arabic']['title'] = $astroConfig['arabic']['title'];
        }
        // 分宮制数据
        $num = 0;
        foreach ($astroConfig['h_sys']['name'] as $k => $datum)
        {
            $tmp = [
                'id' => $k,
                'name' => $astroConfig['h_sys']['name'][$num]['name'],
                'thumb' => $astroConfig['h_sys']['name'][$num]['thumb'],
            ];
            //十二分盘和十三分盘和福点盘默认只能整宫制
            if (in_array($param['chart'], ['fortune', 'zodrel', 'dodekatemorion', 'trimsamsa']))
            {
                if (strcasecmp($datum['thumb'], 'w') === 0)
                {
                    $tmp['status'] = 1;
                } else
                {
                    $tmp['status'] = 2;//不可选中
                }
            } else
            {
                if (strcasecmp($data['h_sys'], $datum['thumb']) === 0)
                {
                    $tmp['status'] = 1;
                } else
                {
                    $tmp['status'] = 0;
                }
            }

            $arr['h_sys']['list'][] = $tmp;

            $num += 1;
        }
        $arr['h_sys']['select_status'] = $astroConfig['h_sys']['select_status'];
        $arr['h_sys']['title'] = $astroConfig['h_sys']['title'];
        //法达数据
        if (strcasecmp($param['chart'], 'firdaria') === 0)
        {
            foreach ($astroConfig['firdaria']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['firdaria']['name'][$k],
                    'status' => 0,
                ];
                if ($k == $data['firdaria'])
                {
                    $tmp['status'] = 1;
                }
                $arr['firdaria']['list'][] = $tmp;
            }

            $arr['firdaria']['select_status'] = $astroConfig['firdaria']['select_status'];
            $arr['firdaria']['title'] = $astroConfig['firdaria']['title'];
        }
        // 小限推运数据
        if (strcasecmp($param['chart'], 'profection') === 0)
        {
            foreach ($astroConfig['profection_push_direction']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['profection_push_direction']['name'][$k],
                    'status' => 0,
                ];
                if ($k == $data['profection_push_direction'])
                {
                    $tmp['status'] = 1;
                }
                $arr['profection_push_direction']['list'][] = $tmp;
            }
            $arr['profection_push_direction']['select_status'] = $astroConfig['profection_push_direction']['select_status'];
            $arr['profection_push_direction']['title'] = $astroConfig['profection_push_direction']['title'];
        }
        // 十度主星数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination']))
        {
            foreach ($astroConfig['decanates']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['decanates']['name'][$k],
                    'status' => 0,
                ];
                if ($k == $data['decanates'])
                {
                    $tmp['status'] = 1;
                }
                $arr['decanates']['list'][] = $tmp;
            }
            $arr['decanates']['select_status'] = $astroConfig['decanates']['select_status'];
            $arr['decanates']['title'] = $astroConfig['decanates']['title'];
        }
        // 界主星数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination']))
        {
            foreach ($astroConfig['bound_type']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['bound_type']['name'][$k],
                    'status' => 0,
                ];
                if ($k == $data['bound_type'])
                {
                    $tmp['status'] = 1;
                }
                $arr['bound_type']['list'][] = $tmp;
            }
            $arr['bound_type']['select_status'] = $astroConfig['bound_type']['select_status'];
            $arr['bound_type']['title'] = $astroConfig['bound_type']['title'];
        }
        // 推运数据
        if (strcasecmp($param['chart'], 'zodrel') === 0)
        {
            foreach ($astroConfig['push_fortune']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['push_fortune']['name'][$k],
                    'status' => 0,
                ];
                if ($k == $data['push_fortune'])
                {
                    $tmp['status'] = 1;
                }
                $arr['push_fortune']['list'][] = $tmp;
            }
            $arr['push_fortune']['select_status'] = $astroConfig['push_fortune']['select_status'];
            $arr['push_fortune']['title'] = $astroConfig['push_fortune']['title'];
        }
        // 返照地点选择
        if (in_array($param['chart'], ['solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal']))
        {
            foreach ($astroConfig['location_use']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['location_use']['name'][$k],
                    'status' => 0,
                ];
                if ((isset($data['location_use']) && $k == $data['location_use']) || ($k === 0 && !isset($data['location_use'])))
                {
                    $tmp['status'] = 1;
                }
                $arr['location_use']['list'][] = $tmp;
            }
            $arr['location_use']['select_status'] = $astroConfig['location_use']['select_status'];
            $arr['location_use']['title'] = $astroConfig['location_use']['title'];
        }
        // 中点类型
        foreach ($astroConfig['mid_type']['name'] as $k => $v)
        {
            $tmp = [
                'id' => $k,
                'name' => $v,
                'status' => ((isset($data['mid_type']) && $k == $data['mid_type']) || ($k === 0 && !isset($data['mid_type']))) ? 1 : 0,
            ];
            $arr['mid_type']['list'][] = $tmp;
        }
        $arr['mid_type']['select_status'] = $astroConfig['mid_type']['select_status'];
        $arr['mid_type']['title'] = $astroConfig['mid_type']['title'];

        $arr['is_default'] = $data['is_default'];

        return $arr;
    }

    /**
     * 旧星盘数据重新调整
     * @param $param
     * @param $data
     * @param $astroConfig
     * @return array
     */
    public function OldAstroData($param, $data, $astroConfig)
    {
        $arr = [];
        // 相位数据
        foreach ($data['asp_orb_all'] as $k => $a)
        {
            // 相位开关默认不显示
            $status = 0;
            // 相位的开关
            foreach ($data['asps_display'] as $b)
            {
                if ($b == $k)
                {
                    $status = 1;
                }
            }

            // 相位数据重组
            foreach ($astroConfig['phase']['name'] as $kk => $item)
            {
                if (in_array((int)$item, [72, 144])) continue;

                if ($k == $item)
                {
                    $arr['phase']['list'][] = [
                        'id' => $kk,
                        'name' => $item . '°',
                        'status' => $status,
                        'allowedness' => $a,
                    ];
                }
            }
        }
        // 相位选项类型,1=>单选,1=>多选
        $arr['phase']['select_status'] = $astroConfig['phase']['select_status'];
        $isAncient = $param['tid'] == 2;
        // 相位容许度开关,默认古典盘不显示
        $arr['phase']['title'] = '相位';

        // 行星数据
        $strLen = strlen($data['planets_display']);
        for ($i = 0; $i < $strLen; $i++)
        {
            switch (true)
            {
                // 行星
                case in_array($i, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
                    if ($data['planets_display'][$i] == 1)
                    {
                        $planet_status = 1;
                    } else
                    {
                        $planet_status = 0;
                    }
                    $arr['planet']['list'][] = [
                        'id' => $i,
                        'name' => $astroConfig['planet']['name'][$i],
                        'status' => $planet_status,
                        'allowedness' => $data['planet_orb_all'][$i] ?? 0,
                    ];
                    $arr['planet']['select_status'] = $astroConfig['planet']['select_status'];
                    $arr['planet']['title'] = '行星';
                    break;
                // 虚点
                case in_array($i, [10, 11, 12, 13, 14, 15, 16]):
                    if ($data['planets_display'][$i] == 1)
                    {
                        $planet_status = 1;
                    } else
                    {
                        $planet_status = 0;
                    }
                    $arr['little_planet']['list'][] = [
                        'id' => $i,
                        'name' => $astroConfig['planet']['name'][$i],
                        'status' => $planet_status,
                        'allowedness' => 0,
                    ];
                    $arr['little_planet']['select_status'] = $astroConfig['planet']['select_status'];
                    $arr['little_planet']['title'] = '虚点';
                    break;
                // 四轴
                case in_array($i, [17, 18, 19, 20]):
                    if ($data['planets_display'][$i] == 1)
                    {
                        $planet_status = 1;
                    } else
                    {
                        $planet_status = 0;
                    }
                    $arr['four_axis']['list'][] = [
                        'id' => $i,
                        'name' => $astroConfig['planet']['name'][$i],
                        'status' => $planet_status,
                        'allowedness' => 0,
                    ];
                    $arr['four_axis']['select_status'] = $astroConfig['planet']['select_status'];
                    $arr['four_axis']['title'] = '四轴';
                    break;
            }

        }
        // 希腊点数据
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'transits', 'synastry', 'divination']) && isset($data['arabic']))
        {
            foreach ($data['arabic'] as $k => $datum)
            {
                if ($k > 8) break 1;
                $status = $datum[0] ? 1 : 0;
                $arr['arabic']['list'][] = [
                    'id' => $k,
                    'name' => $astroConfig['arabic']['name'][$k],
                    'status' => $status,
                    'allowedness' => 0,
                ];
            }
            $arr['arabic']['select_status'] = $astroConfig['arabic']['select_status'];
            $arr['arabic']['title'] = $astroConfig['arabic']['title'];
        }

        $arr['planet']['allowedness_switch'] =
        $arr['little_planet']['allowedness_switch'] =
        $arr['four_axis']['allowedness_switch'] = $param['tid'] > 1 ? 1 : 0;
        $arr['phase']['allowedness_switch'] = $isAncient ? 0 : 1;
        // 分宮制
        foreach ($astroConfig['h_sys']['name'] as $k => $datum)
        {
            // 十二分盘和十三分盘和福点盘默认只能整宫制
            if (in_array($param['chart'], ['fortune', 'zodrel', 'dodekatemorion', 'trimsamsa']))
            {
                if (strcasecmp($datum['thumb'], 'w') === 0)
                {
                    $status = 1;
                } else
                {
                    $status = 2;// 不可选中
                }
            } else
            {
                if ($data['h_sys'] == $datum['thumb'])
                {
                    $status = 1;
                } else
                {
                    $status = 0;
                }
            }

            $arr['h_sys']['list'][] = [
                'id' => $k,
                'name' => $datum['name'],
                'thumb' => $datum['thumb'],
                'status' => $status,
            ];
        }
        $arr['h_sys']['select_status'] = $astroConfig['h_sys']['select_status'];
        $arr['h_sys']['title'] = $astroConfig['h_sys']['title'];

        // 法达星序
        if (strcasecmp($param['chart'], 'firdaria') === 0 && isset($data['firdaria']))
        {
            foreach ($astroConfig['firdaria']['name'] as $k => $datum)
            {
                if ($data['firdaria'] == $k)
                {
                    $status = 1;
                } else
                {
                    $status = 0;
                }

                $arr['firdaria']['list'][] = [
                    'id' => $k,
                    'name' => $datum,
                    'status' => $status,
                ];
            }
            $arr['firdaria']['select_status'] = $astroConfig['firdaria']['select_status'];
            $arr['firdaria']['title'] = $astroConfig['firdaria']['title'];
        }

        // 小限推运方向
        if (strcasecmp($param['chart'], 'profection') === 0 && isset($data['profection_push_direction']))
        {
            foreach ($astroConfig['profection_push_direction']['name'] as $k => $datum)
            {
                if ($data['profection_push_direction'] == $k)
                {
                    $status = 1;
                } else
                {
                    $status = 0;
                }

                $arr['profection_push_direction']['list'][] = [
                    'id' => $k,
                    'name' => $datum,
                    'status' => $status,
                ];
            }
            $arr['profection_push_direction']['select_status'] = $astroConfig['profection_push_direction']['select_status'];
            $arr['profection_push_direction']['title'] = $astroConfig['profection_push_direction']['title'];
        }
        // 十度主星
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination']) && isset($data['decanates']))
        {
            foreach ($astroConfig['decanates']['name'] as $k => $datum)
            {
                if ($data['decanates'] == $k)
                {
                    $status = 1;
                } else
                {
                    $status = 0;
                }

                $arr['decanates']['list'][] = [
                    'id' => $k,
                    'name' => $datum,
                    'status' => $status,
                ];
            }
            $arr['decanates']['select_status'] = $astroConfig['decanates']['select_status'];
            $arr['decanates']['title'] = $astroConfig['decanates']['title'];
        }
        // 界主星
        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination']) && isset($data['bound_type']))
        {
            foreach ($astroConfig['bound_type']['name'] as $k => $datum)
            {
                if ($data['bound_type'] == $k)
                {
                    $status = 1;
                } else
                {
                    $status = 0;
                }

                $arr['bound_type']['list'][] = [
                    'id' => $k,
                    'name' => $datum,
                    'status' => $status,
                ];
            }
            $arr['bound_type']['select_status'] = $astroConfig['bound_type']['select_status'];
            $arr['bound_type']['title'] = $astroConfig['bound_type']['title'];
        }
        // 推运
        if (strcasecmp($param['chart'], 'zodrel') === 0 && isset($data['push_fortune']))
        {
            foreach ($astroConfig['push_fortune']['name'] as $k => $datum)
            {
                if ($data['push_fortune'] == $k)
                {
                    $status = 1;
                } else
                {
                    $status = 0;
                }

                $arr['push_fortune']['list'][] = [
                    'id' => $k,
                    'name' => $datum,
                    'status' => $status,
                ];
            }
            $arr['push_fortune']['select_status'] = $astroConfig['push_fortune']['select_status'];
            $arr['push_fortune']['title'] = $astroConfig['push_fortune']['title'];
        }

        // 返照地点选择
        if (in_array($param['chart'], ['solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal'], true))
        {
            foreach ($astroConfig['location_use']['name'] as $k => $datum)
            {
                $tmp = [
                    'id' => $k,
                    'name' => $astroConfig['location_use']['name'][$k],
                    'status' => 0,
                ];
                if ((isset($data['location_use']) && $k == $data['location_use']) || ($k === 0 && !isset($data['location_use'])))
                {
                    $tmp['status'] = 1;
                }
                $arr['location_use']['list'][] = $tmp;
            }
            $arr['location_use']['select_status'] = $astroConfig['location_use']['select_status'];
            $arr['location_use']['title'] = $astroConfig['location_use']['title'];
        }

        $arr['is_default'] = $data['is_default'];
        return $arr;
    }

    /**
     * 验证客户端传递的参数是否正确
     * @param array $param
     * @return bool|string
     */
    private function checkParamAstroSetting($param = [])
    {
        try
        {
            if (!isset($param['chart']) || !in_array($param['chart'], config('astroset175.chart'), true))
            {
                return '未知星盘';
            }
            if (count($param['planet']['list']) !== 10)
            {
                return '行星设置失败';
            }

            if (count($param['phase']['list']) !== 13)
            {
                return '相位设置失败';
            }

            if (count($param['little_planet']['list']) !== 7)
            {
                return '虚点设置失败';
            }

            if (count($param['four_axis']['list']) !== 4)
            {
                return '四轴设置失败';
            }

            if (count($param['h_sys']['list']) !== 12)
            {
                return '分宫制设置失败';
            }

            // 包含界主星和十度主星的星盘
            $ContainBoundDecanatesCharts = ['natal', 'now', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'divination'];

            // 包含希腊点的星盘
            $ContainArabicsCcharts = ['natal', 'now', 'profection', 'firdaria', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa', 'transits', 'synastry', 'divination'];

            // 黄道星释盘验证
            if ($param['chart'] === 'zodrel' && (!isset($param['push_fortune']) || count($param['push_fortune']) > 20))
            {
                return '推运基点参数错误';
            }

            // 小限盘参数验证
            if ($param['chart'] === 'profection' && (!isset($param['profection_push_direction']['list']) || count($param['profection_push_direction']['list']) !== 2))
            {
                return '小限推运方向参数错误';
            }

            if (in_array($param['chart'], $ContainBoundDecanatesCharts, true) && (!isset($param['bound_type']['list']) || count($param['bound_type']['list']) !== 2))
            {
                return '界主星参数错误';
            }

            if (in_array($param['chart'], $ContainBoundDecanatesCharts, true) && (!isset($param['decanates']['list']) || count($param['decanates']['list']) !== 2))
            {
                return '十度主星参数错误';
            }

            if (in_array($param['chart'], $ContainArabicsCcharts, true) && (!isset($param['arabic']['list']) || count($param['arabic']['list']) !== 9))
            {
                return '希腊点参数错误';
            }
            // 返照地点参数验证
            if (in_array($param['chart'], ['solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal'], true) && (!isset($param['location_use']['list']) || count($param['location_use']['list']) !== 2))
            {
                $version = $this->request->header('version');
                // 版本1.9.3及以下不检测该参数，参数为1.9.4新增
                if ((float)$version >= 1.9 && !in_array($version, ['1.9.0', '1.9.1', '1.9.2', '1.9.3'], true))
                {
                    return '返照地点参数错误';
                }
            }
        }
        catch (\Exception $e)
        {
            return $e->getMessage();
        }

        return true;
    }


    /**
     * 验证客户端传递的参数是否正确【只有 占星师平台 和 天象盘】
     * @param array $param 参数
     * @param bool $is_astrologer 是否是占星师平台 true：占星师平台；false：天象盘
     * @return bool|string
     */
    private function checkParamAstro($param = [], $is_astrologer = false)
    {
        if (!isset($param['chart']) || !in_array($param['chart'], config('astroset175.chart'), true))
        {
            return '未知星盘';
        }

        if (!$is_astrologer)
        {// 天象盘验证
            if ($param['chart'] === 'now' && (!isset($param['longitude'], $param['latitude'])))
            {
                return '参数错误';
            }
            if (!isset($param['datetime']) || strtotime($param['datetime']) === false)
            {
                return '时间错误';
            }

            if (!isset($param['timezone']) || $param['timezone'] > 12 || $param['timezone'] < -12)
            {
                return '时区错误';
            }
        } else
        {//占星师平台验证
            // chart检测
            if (!in_array($param['chart'], self::PARAMS_SINGLE, true) && !in_array($param['chart'], self::PARAMS_DOUBLE, true) && !in_array($param['chart'], self::PARAMS_ADVANCE, true) && !in_array($param['chart'], self::PARAMS_SYNASTRY, true))
            {
                return 'chart参数错误';
            }
            // 推进盘验证
            if (in_array($param['chart'], self::PARAMS_ADVANCE, true))
            {
                if (!isset($param['datetime']) || strtotime($param['datetime']) === false)
                {
                    return '时间错误';
                }

                if (!isset($param['timezone']) || $param['timezone'] > 12 || $param['timezone'] < -12)
                {
                    return '时区错误';
                }
            }

        }

        return true;
    }
}
